package com.yimi.yinhepda.views.offline.load;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pda.ym.base.BaseTitleActivity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.db.dao.CarPlateTableDao;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.pda.ym.db.table.CarPlateTable;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.pda.ym.utils.ProvinceEnum;
import com.pda.ym.utils.CarNoSelectDialog;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.pda.uce.commom.util.LogUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.yimi.yinhepda.views.createPackage_module.CreateDeptSelectActivity;
import com.yimi.yinhepda.views.load_module.ScanSealSignActivity;

import org.jetbrains.annotations.NotNull;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * 离线装车成功界面.
 *
 * @author lj
 */
public class OffLineLoadSuccessActivity extends BaseTitleActivity implements TextWatcher {

    private EditText etTaskNo;
    private Button btnCarPlate;
    private EditText etCarNo;
    private String offlineTaskNo;
    private String userCode;
    private TextView tvDestDept;
    private TextView tvStowageNo;
    private String mDeptCode;
    private String mDeptName;
    private String lineType;
    private String toCompany;
    private UnloadTaskTable taskTable;
    private UnloadTaskTableDao taskTableDao;
    private CheckBox cbCompleteCar;
    /**
     * 离线装车类型：1-离线装车，2-离线卸车,3-单独封车
     */
    private int loadType;
    /**
     * 临时转换的车牌号
     */
    private String mTempCarNo = "";
    private int operTypeCode = 3;

    public OffLineLoadSuccessActivity() {
        super(true);
    }

    @Override
    public String getPageName() {
        return "离线装车成功";
    }

    @Override
    public int setContentViewId() {
        return R.layout.activity_offline_load_success;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //配载单号
        tvStowageNo = findViewById(R.id.et_stowageNo);
        //离线号
        EditText etOfflineTaskNo = findViewById(R.id.et_offline_taskNo);
        //任务号
        etTaskNo = findViewById(R.id.et_taskNo);
        //车牌按钮
        btnCarPlate = findViewById(R.id.btn_carPlate);
        btnCarPlate.setOnClickListener(this);
        //车牌号
        etCarNo = findViewById(R.id.et_carNo);
        etCarNo.addTextChangedListener(this);
        //出发部门
        EditText etSrcDept = findViewById(R.id.et_src_dept);
        //到达部门
        tvDestDept = findViewById(R.id.et_dest_dept);
        tvDestDept.setOnClickListener(this);
        //装车票数
        EditText etPiaoNum = findViewById(R.id.et_piaoNum);
        //装车件数
        EditText etJianNum = findViewById(R.id.et_jianNum);
        findViewById(R.id.btn_sure).setOnClickListener(this);
        LinearLayout llLoadPiao = findViewById(R.id.ll_load_piao);
        LinearLayout llLoadJian = findViewById(R.id.ll_load_jian);
        TextView tvDestDeptFlag = findViewById(R.id.tv_destDept_flag);
        LinearLayout llStowageNo = findViewById(R.id.ll_stowageNo);
        LinearLayout llOfflineTaskNo = findViewById(R.id.ll_offline_taskNo);
        TextView tvLoadSuccess = findViewById(R.id.tv_loadSucess);
        LinearLayout llCompleteCar = findViewById(R.id.ll_completeCar);
        cbCompleteCar = findViewById(R.id.cb_completeCar);

        taskTableDao = new UnloadTaskTableDao();

        //设置车牌
        List<CarPlateTable> carPlateTables = new CarPlateTableDao().getAllData();
        if (carPlateTables != null && !carPlateTables.isEmpty()) {
            btnCarPlate.setText(carPlateTables.get(0).getCarPlate());
        }

        userCode = sharedPreferUtil.getValue(Common.USER_CODE);

        //离线装车类型
        loadType = getIntent().getIntExtra("loadType", 0);
        if (loadType == 1) {
            //离线装车
            offlineTaskNo = getIntent().getStringExtra("offlineTaskNo");
            String srcDept = getIntent().getStringExtra("srcDept");
            String destDept = getIntent().getStringExtra("destDept");
            String loadPiaoNum = getIntent().getStringExtra("loadPiaoNum");
            String loadJianNum = getIntent().getStringExtra("loadJianNum");
            lineType = getIntent().getStringExtra("lineType");

            taskTable = taskTableDao.findData(offlineTaskNo, sharedPreferUtil.getValue(Common.USER_CODE));
            if (taskTable != null) {
                etTaskNo.setText(taskTable.getTask());
                String carNo = taskTable.getCarNo();
                if (carNo.length() > 0) {
                    btnCarPlate.setText(carNo.substring(0, 1));
                    etCarNo.setText(carNo.substring(1, carNo.length()));
                }
                if (taskTable.getIsCompleteCar() == 1) {
                    cbCompleteCar.setChecked(true);
                }
            }
            etOfflineTaskNo.setText(offlineTaskNo);
            etSrcDept.setText(srcDept);
            tvDestDept.setText(destDept);
            etPiaoNum.setText(loadPiaoNum);
            etJianNum.setText(loadJianNum);
            etOfflineTaskNo.setEnabled(false);
            etOfflineTaskNo.setBackgroundColor(getResources().getColor(R.color.gray));
            etSrcDept.setEnabled(false);
            etSrcDept.setBackgroundColor(getResources().getColor(R.color.gray));
            tvDestDept.setEnabled(false);
            tvDestDept.setBackgroundColor(getResources().getColor(R.color.gray));
            etPiaoNum.setEnabled(false);
            etPiaoNum.setBackgroundColor(getResources().getColor(R.color.gray));
            etJianNum.setEnabled(false);
            etJianNum.setBackgroundColor(getResources().getColor(R.color.gray));
            tvDestDeptFlag.setVisibility(View.GONE);
            llStowageNo.setVisibility(View.GONE);
        } else if (loadType == 3) {
            //单独封车
            setTitle("单独封车");
            offlineTaskNo = getIntent().getStringExtra("offlineTaskNo");
            taskTable = taskTableDao.findData(offlineTaskNo, sharedPreferUtil.getValue(Common.USER_CODE));
            if (taskTable != null) {
                tvStowageNo.setText(taskTable.getStowageNo());
                etTaskNo.setText(taskTable.getTask());
                String carNo = taskTable.getCarNo();
                if (carNo.length() > 0) {
                    btnCarPlate.setText(carNo.substring(0, 1));
                    etCarNo.setText(carNo.substring(1, carNo.length()));
                }
                mDeptCode = taskTable.getDestDeptCode();
                mDeptName = taskTable.getDestDeptName();
                lineType = taskTable.getBizTypeCode() + "";
                toCompany = taskTable.getToCompCode();
                tvDestDept.setText(mDeptName);
            }
            etSrcDept.setText(sharedPreferUtil.getValue(Common.DEPT_NAME));
            etSrcDept.setBackgroundColor(getResources().getColor(R.color.gray));
            tvDestDept.setOnClickListener(this);
            etSrcDept.setEnabled(false);
            llLoadPiao.setVisibility(View.GONE);
            llLoadJian.setVisibility(View.GONE);
            llOfflineTaskNo.setVisibility(View.GONE);
            tvLoadSuccess.setVisibility(View.GONE);
            llCompleteCar.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_carPlate:
                //显示车牌对话框提示框
                CarNoSelectDialog.showCarPlateDialog(this, new CarNoSelectDialog.CarNoSelectListener() {
                    @Override
                    public void onclick(String carPlate) {
                        btnCarPlate.setText(carPlate);
                    }
                });
                break;
            case R.id.et_dest_dept:
                Intent intent = new Intent(this, CreateDeptSelectActivity.class);
                intent.putExtra("currentDept", sharedPreferUtil.getDeptCode());
                intent.putExtra("inputType", 1);
                startActivityForResult(intent, 0);
                break;
            case R.id.btn_sure:
                if (loadType == 1) {
                    //装车类型：离线装车
                    offlineLoadSubmit();
                } else if (loadType == 3) {
                    //单独封车
                    singleSealCarSubmit();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 0) {
            mDeptCode = data.getStringExtra("deptCode");
            mDeptName = data.getStringExtra("deptName");
            lineType = data.getStringExtra("lineType");
            toCompany = data.getStringExtra("toCompany");
            tvDestDept.setText(mDeptName);
        }
    }

    /**
     * 单独封车提交
     */
    private void singleSealCarSubmit() {
//        int count = (int) new UnloadScanTableDao().queryCount("isUpload", 0, operTypeCode, userCode);
//        if (count > 9) {
//            Toast.makeText(this, "你的离线任务很多啊，兄弟", Toast.LENGTH_SHORT).show();
//            //开启扫描
//            setScannerEnabled(true);
//            SoundVibratorManager.playSound(2);
//            return;
//        }

        String carNo = etCarNo.getText().toString();
        if (carNo.equals("")) {
            showToast("请输入车牌号！");
            return;
        }
        String destDept = tvDestDept.getText().toString();
        if (destDept.equals("")) {
            showToast("请选择到达部门！");
            return;
        }
        String carPlate = btnCarPlate.getText().toString();
        String stowageNo = tvStowageNo.getText().toString();

        //同样始发站-目的站-日期条件下，的order
        Integer order = taskTableDao.findByTime(DateHelper.getDateFormateShort(new Date()),
                sharedPreferUtil.getDeptCode(), mDeptCode, userCode);
        order = order == null ? 1 : order + 1;

        //离线任务号
        if (offlineTaskNo == null) {
            offlineTaskNo = "Z" + DateHelper.getDateTimeFormateForSimple4(new Date()) + mDeptCode + order;
        }
        boolean isNull = false;
        if (taskTable == null) {
            isNull = true;
            //创建配载单
            taskTable = new UnloadTaskTable();
        }
        taskTable.setTask(etTaskNo.getText().toString().trim());
        taskTable.setCreateTime(Constants.getCurrentTimeFormat1());
        taskTable.setShowTime(DateHelper.getDateFormateShort(new Date()));
        //车牌号
        taskTable.setCarNo(carPlate + carNo);
        //目的站code
        taskTable.setDestDeptCode(mDeptCode);
        //目的站名称
        taskTable.setDestDeptName(mDeptName);
        //始发站code
        taskTable.setSrcDeptCode(sharedPreferUtil.getDeptCode());
        //始发站名称
        taskTable.setSrcDeptName(sharedPreferUtil.getValue(Common.DEPT_NAME));
        // 序号
        taskTable.setOrder(order);
        //操作员工
        taskTable.setOperEmpCode(userCode);
        //干线，支线
        taskTable.setBizTypeCode(Integer.parseInt(lineType));
        //配载单
        taskTable.setStowageNo(stowageNo);
        //离线任务号
        taskTable.setOfflineTaskNo(offlineTaskNo);
        taskTable.setToCompCode(toCompany);
        taskTable.setStatus(0);
        //单独封车
        taskTable.setLoadType(6);
        try {
            if (isNull) {
                taskTableDao.insert(taskTable);
            } else {
                taskTableDao.update(taskTable);
            }
        } catch (SQLException e) {
            LogUtil.e(e.toString());
        }

        finish();

        //跳转至封签扫描界面
        Intent intent = new Intent(OffLineLoadSuccessActivity.this, ScanSealSignActivity.class);
        //装车类型：1-离线装车类型,2-离线卸车，3-单独封车
        intent.putExtra("loadType", 3);
        intent.putExtra("offlineTaskNo", offlineTaskNo);
        intent.putExtra("carPlateNo", carPlate + carNo);
        intent.putExtra("lineType", lineType);
        startActivity(intent);
    }

    /**
     * 离线装车提交
     */
    private void offlineLoadSubmit() {
        final String carNo = etCarNo.getText().toString();
        if (carNo.equals("")) {
            showToast("请输入车牌号！");
            return;
        }
        String taskNo = etTaskNo.getText().toString();
        String carPlate = btnCarPlate.getText().toString();
        String carPlateNo = carPlate + carNo;
        UnloadTaskTableDao unloadTaskTableDao = new UnloadTaskTableDao();
        UnloadTaskTable unloadTaskTable = unloadTaskTableDao.findData(offlineTaskNo, userCode);
        unloadTaskTable.setTask(taskNo);
        unloadTaskTable.setCarNo(carPlateNo);
        //是否是整车：1-是，2-否
        if (cbCompleteCar.isChecked()) {
            unloadTaskTable.setIsCompleteCar(1);
        } else {
            unloadTaskTable.setIsCompleteCar(2);
        }
        try {
            unloadTaskTableDao.update(unloadTaskTable);
        } catch (SQLException e) {
            LogUtil.e(e.toString());
        }
        finish();
        //跳转至封签界面
        Intent intent = new Intent(OffLineLoadSuccessActivity.this, ScanSealSignActivity.class);
        //装车类型：1-离线装车类型,2-离线卸车，3-单独封车
        intent.putExtra("loadType", 1);
        intent.putExtra("offlineTaskNo", offlineTaskNo);
        intent.putExtra("carPlateNo", carPlateNo);
        intent.putExtra("lineType", lineType);
        startActivity(intent);
    }

    @Override
    protected void handleBarCode(String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号扫描失败");
        } else {
            if (result.contains(Common.SP_C_)) {
                etCarNo.setText(result.split(Common.SP_C_)[1]);
                btnCarPlate.setText(ProvinceEnum.getByCode(result.split(Common.SP_C_)[0]).getName());
                SoundVibratorManager.playSound(1);
            } else {
                doScan(result);
            }
        }
    }

    /**
     * 扫描任务号
     *
     * @param result 任务号
     */
    private void doScan(String result) {
        etTaskNo.setText(result);
        SoundVibratorManager.playSound(1);
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        //车牌号英文字母转换成大写
        String carNo = etCarNo.getText().toString().toUpperCase();
        if (!carNo.equalsIgnoreCase(mTempCarNo)) {
            mTempCarNo = carNo;
            etCarNo.setText(carNo);
            etCarNo.setSelection(carNo.length());
        }
    }

    @Override
    public boolean showBack() {
        return false;
    }

    @Override
    public void setBack() {

    }

    @NotNull
    @Override
    public String setTitle() {
        return getPageName();
    }

}
